/* Octopus PDF - A simple document viewer for Android.
   Copyright (C) 2013  Gerald Thaler

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */
package de.geraldthaler.octopuspdf.docrender;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @author Gerald Thaler
 */
public final class DocSource {
    public static final int DOC_TYPE_CBZ = 1;
    public static final int DOC_TYPE_PDF = 2;
    public static final int DOC_TYPE_XPS = 3;

    private static final int SEEK_SET = 0;
    private static final int SEEK_CUR = 1;
    private static final int SEEK_END = 2;

    private final byte[] buffer = new byte[4096];
    private final int docType;
    private final File file;
    private RandomAccessFile raFile;

    public DocSource(final File file, final int docType) {
        this.file = file;
        this.docType = docType;
    }
    
    public void close() throws IOException {
        raFile.close();
    }

    public byte[] getBuffer() {
        return buffer;
    }

    public int getDocType() {
        return docType;
    }

    public int read(int len) throws IOException {
        if (len > buffer.length)
            len = buffer.length;
        return raFile.read(buffer, 0, len);
    }

    public void open() throws IOException {
        raFile = new RandomAccessFile(file, "r");
    }

    public int seek(final int offset, final int whence) throws IOException {
        switch (whence) {
        case SEEK_SET:
            raFile.seek(offset);
            break;
        case SEEK_CUR:
            raFile.seek(raFile.getFilePointer() + offset);
            break;
        case SEEK_END:
            raFile.seek(raFile.length() - offset);
            break;
        default:
        	// nothing
        }
        return (int) raFile.getFilePointer();
    }
}
